package com.zhonghui.dolo.manager.controller;

import com.zhonghui.dolo.manager.model.vo.AdminVo;
import com.zhonghui.dolo.manager.model.vo.ModuleVo;
import com.zhonghui.dolo.manager.service.AdminService;
import com.zhonghui.dolo.manager.service.ModuleService;
import com.zhonghui.dolo.manager.util.Constans;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
@RequestMapping("/mgr")
public class AdminController {
    @Autowired
    private AdminService adminService;
    @Autowired
    private ModuleService moduleService;
    
    @RequestMapping("/login")
    public ModelAndView login(@RequestParam("uname") String uname, @RequestParam("upwd") String upwd, HttpServletRequest request, ModelAndView modelAndView) {
        AdminVo adminVo = adminService.login(uname, upwd);
        // 登陆失败
        if (adminVo == null) {
            modelAndView.addObject("result", "用户名或密码错误");
            modelAndView.setViewName("login");
            return modelAndView;
        }
        // 登陆成功
        request.getSession().setAttribute("admin", adminVo);
        // 设置权限菜单
        List<ModuleVo> moduleVoList = null;
        if (adminVo.getRoleId() == Constans.Role.ADMIN) {
            moduleVoList = moduleService.queryUserModel();
        } else {
            moduleVoList = moduleService.queryUserModelByRoleId(adminVo.getRoleId());
        }
        request.getSession().setAttribute("moduleVoList", moduleVoList);
        modelAndView.addObject("admin", adminVo);
        modelAndView.addObject("moduleVoList", moduleVoList);
        modelAndView.setViewName(Constans.ViewName.INDEX);
        return modelAndView;
    }
}
